package com.example.shardingdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.*;

//自定义分表规则类 引用基因法
@Slf4j
public class OrderShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection  availableTargetNames, ComplexKeysShardingValue  shardingValue) {

        Map<String, Object> columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        System.out.println("OrderShardingAlgorithm所有的sharding列的值为"+columnNameAndShardingValuesMap);
        Set<String> result = new HashSet<>();
        //uuid路由
        Collection idColl = (Collection)columnNameAndShardingValuesMap.get("uuid");
        //userid路由
        idColl=(null==idColl)?(Collection)columnNameAndShardingValuesMap.get("user_id"):idColl;
        if(null!=idColl){
            for (Object idObj: idColl) {
                if (idObj instanceof Integer || idObj instanceof Long) {
                    long idTemp = Long.parseLong(idObj.toString());
                    long target = idTemp % availableTargetNames.size();
                    for (Object targetNames:availableTargetNames) {
                        if (targetNames.toString().endsWith(target + "")) {
                            result.add(targetNames.toString());
                        }
                    }
                }
            }
        }
        System.out.println("OrderShardingAlgorithm====?complex算法result="+result);
        return result;
    }


}

